package com.inspectortime.admin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

/**
 * Intent: Provide means to invoke the exceptionResolver from outside the Spring
 * context (such as web.xml defined error page)
 * 
 * @author mkvalsvik
 * 
 */
public class ErrorController implements Controller {

	private ExceptionResolver exceptionResolver;

	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {

		// Tomcat
		Throwable t = (Throwable) request.getAttribute("javax.servlet.error.exception");
		if (t == null) {

			// Sun ONE
			t = (Throwable) request.getAttribute("javax.servlet.jsp.jspException");
		}
		if (t == null) {
			t = new RuntimeException("An unknown exception occurred outside the Spring context");
		}
		if (t instanceof Exception) {
			return exceptionResolver.resolveException(request, response, this, (Exception) t);
		}

		throw new Error(t);
	}

	public ExceptionResolver getExceptionResolver() {
		return exceptionResolver;
	}

	public void setExceptionResolver(ExceptionResolver exceptionResolver) {
		this.exceptionResolver = exceptionResolver;
	}

}
